/*
 -----------------------------------------------------------------------------
 This source file is part of FolderProtector
 Copyright (c) 2011, Vyacheslav Chigrin, folderprotector (at) gmail.com  All rights reserved.
 Send your commends
	 ---The BSD 3-Clause License---
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation and/or
  other materials provided with the distribution.
* Neither the name of the Folder Protector project nor the names of its contributors
  may be used to endorse or promote products derived from this software without specific
  prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
  SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  -----------------------------------------------------------------------------
*/
#include <Windows.h>
#include <tchar.h>
#include "CommonKMUM.h"
#include <string>

#define INSTANCE_NAME L"ProtectorInstance"
#define INSTANCE_ALTITUDE L"265000"
#define INSTANCE_FLAGS  0

std::wstring GetDriverPath()
{//assumed that the driver is in same dir. as exe
    wchar_t szExePath[MAX_PATH];
    if(!GetModuleFileName(NULL,szExePath,sizeof(szExePath)/sizeof(szExePath[0])))
        return std::wstring();
    wchar_t* pLastSlash=wcsrchr(szExePath,L'\\');
    if(!pLastSlash)//should never occur
        return std::wstring();
    pLastSlash++;
    wcscpy(pLastSlash,SERVICE_BINARY_NAME);
    return std::wstring(szExePath);
}

bool InstallDriver()
{
    SC_HANDLE hSCM=NULL,hService=NULL;
    hSCM=OpenSCManager(NULL,NULL,SC_MANAGER_ENUMERATE_SERVICE|SC_MANAGER_CREATE_SERVICE);
    bool result=false;
    do
    {
        if(!hSCM)
            break;
        hService=OpenService(hSCM,SERVICE_NAME,SERVICE_QUERY_STATUS|SERVICE_START);
        if(hService)
        {//already exists
            result=true;
            break;
        }
        std::wstring driverPath=GetDriverPath();
        if(driverPath.empty())
            break;
        hService=CreateService(hSCM,
                            SERVICE_NAME,
                            SERVICE_NAME,
                            SERVICE_ALL_ACCESS,
                            SERVICE_KERNEL_DRIVER,
                            SERVICE_AUTO_START,
                            SERVICE_ERROR_NORMAL,
                            driverPath.c_str(),
                            NULL,
                            NULL,
                            NULL,
                            NULL,
                            NULL);
        if(hService)
            result=true;    
    }while(0);
    if(hService)
        CloseServiceHandle(hService);
    if(hSCM)
        CloseServiceHandle(hSCM);
    return result;
}

bool UninstallDriver()
{
    SC_HANDLE hSCM,hService;
    hSCM=OpenSCManager(NULL,NULL,SC_MANAGER_ENUMERATE_SERVICE);
    bool result=false;
    do
    {
        if(!hSCM)
            break;
        hService=OpenService(hSCM,SERVICE_NAME,SERVICE_ALL_ACCESS);
        if(!hService)
            break;
        SERVICE_STATUS stat;
        memset(&stat,0,sizeof(stat));
        QueryServiceStatus(hService,&stat);
        if(stat.dwCurrentState!=SERVICE_STOPPED)
        {//try to stop driver before removing
            ControlService(hService,SERVICE_CONTROL_STOP,&stat);
            //10 sec. wait to service stop
            for(int i=0;i<20;i++)
            {
                if(stat.dwCurrentState==SERVICE_STOPPED)
                    break;
                Sleep(500);
                QueryServiceStatus(hService,&stat);
            }
        }
        if(!DeleteService(hService))
            break;
        result=true;
    }while(0);
    if(hService)
        CloseServiceHandle(hService);
    if(hSCM)
        CloseServiceHandle(hSCM);
    return result;
}

bool RegisterInstance()
{
    HKEY hKeyService=NULL,hKeyInstances=NULL,hKeyInstance=NULL;
    bool result=false;
    do
    {
        if(RegOpenKeyExW(HKEY_LOCAL_MACHINE,L"System\\CurrentControlSet\\Services\\"SERVICE_NAME,0,KEY_CREATE_SUB_KEY,&hKeyService)!=ERROR_SUCCESS)
            break;
        DWORD dwDisposition;
        RegCreateKeyExW(hKeyService,L"Instances",0,NULL,0,KEY_ALL_ACCESS,NULL,&hKeyInstances,&dwDisposition);
        if(!hKeyInstances)
            break;
        if(RegSetValueExW(hKeyInstances,L"DefaultInstance",0,REG_SZ,(const BYTE*)INSTANCE_NAME,(wcslen(INSTANCE_NAME)+1)*sizeof(wchar_t))!=ERROR_SUCCESS)
            break;
        RegCreateKeyExW(hKeyInstances,INSTANCE_NAME,0,NULL,0,KEY_ALL_ACCESS,NULL,&hKeyInstance,&dwDisposition);
        if(!hKeyInstance)
            break;
        if(RegSetValueExW(hKeyInstance,L"Altitude",0,REG_SZ,(const BYTE*)INSTANCE_ALTITUDE,(wcslen(INSTANCE_ALTITUDE)+1)*sizeof(wchar_t))!=ERROR_SUCCESS)
            break;
        DWORD dwFlags=INSTANCE_FLAGS;
        if(RegSetValueExW(hKeyInstance,L"Flags",0,REG_DWORD,(const BYTE*)&dwFlags,sizeof(DWORD))!=ERROR_SUCCESS)
            break;
        result=true;
    }while(0);
    if(hKeyInstance)
        RegCloseKey(hKeyInstance);
    if(hKeyInstances)
        RegCloseKey(hKeyInstances);
    if(hKeyService)
        RegCloseKey(hKeyService);
    return result;
}

bool SetDefaultParameters()
{
    HKEY hKeyParameters=NULL;
    bool result=false;
    do
    {
        DWORD dwDisposition;
        RegCreateKeyExW(HKEY_LOCAL_MACHINE,L"System\\CurrentControlSet\\Services\\"SERVICE_NAME\
            L"\\Parameters",0,NULL,0,KEY_SET_VALUE,NULL,&hKeyParameters,&dwDisposition);
        if(!hKeyParameters)
            break;
        DWORD dwZero=0;
        if(RegSetValueEx(hKeyParameters,HIDING_ENABLED_VALUE,0,REG_DWORD,(const BYTE*)&dwZero,sizeof(dwZero))!=ERROR_SUCCESS)
            break;
        wchar_t szEmpty[2];
        szEmpty[0]=szEmpty[1]=L'\0';
        if(RegSetValueEx(hKeyParameters,HIDDEN_PATHS_VALUE,0,REG_MULTI_SZ,(const BYTE*)szEmpty,sizeof(szEmpty))!=ERROR_SUCCESS)
            break;
        result=true;
    }while(0);
    if(hKeyParameters)
        RegCloseKey(hKeyParameters);
    return result;
}

int WINAPI wWinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPWSTR lpCmdLine,int nCmdShow)
{
	int argc=0;
    LPWSTR *pArgs=CommandLineToArgvW(GetCommandLine(),&argc);
    bool isCmdLineOk=false,isOk=false;
    do
    {
        if(argc<2)
            break;
        if(wcscmp(pArgs[1],L"-install")==0)
        {
            isCmdLineOk=true;
            isOk=InstallDriver();
            isOk&=RegisterInstance();
            isOk&=SetDefaultParameters();
        }
        else if(wcscmp(pArgs[1],L"-uninstall")==0)
        {
            isCmdLineOk=true;
            isOk=UninstallDriver();
        }
    }
    while(0);
    if(!isCmdLineOk)
    {
        MessageBox(NULL,_T("Usage: DriverInstaller.exe [-install|-uninstall]"),_T("Driver Installer"),MB_OK|MB_ICONINFORMATION);
    }
    return isOk?0:1;
}